<template>
    <div>
        <van-nav-bar class="navBar" title="我的月租车" left-text="返回" left-arrow @click-left="onClickLeft" fixed/>
        <div class="mainWrap fixedMain">
            <van-list
                :finished="finished"
                :immediate-check="false"
                v-model="loading"
                finished-text=""
                @load="onLoad"
                :offset="10"
                >
                <div class="searchWrap">
                    <van-button type="info" size="mini" @click="apply">月租申请</van-button>
                </div>
                <van-card  class="vanCard" v-for="(item,index) in monthlyCarList" :key="index">
                    <template #title>
                        <van-row type="flex" justify="center" >
                            <van-col span="14">{{item.parkName}}</van-col>
                            <van-col span="7">{{item.licensePlate}}</van-col>
                            <van-col span="3">
                                <van-button type="info" size="mini" @click="jumpPay(item)">续费</van-button>
                            </van-col>
                        </van-row>
                        <van-row type="flex" justify="center" >
                            <van-col span="14">到期时间：{{item.endTime}}</van-col>
                            <van-col span="7">{{getDayNum(item.endTime)>0?'剩余'+getDayNum(item.endTime)+'天':"过期"}}</van-col>
                            <van-col span="3">
                            </van-col>
                        </van-row>
                    </template>
                </van-card>
                <div class="noSearch" v-if="monthlyCarList.length == 0">暂无查询数据</div>
            </van-list>
        </div>
        <!-- 弹框 -->
        <div class="covers mycarDialog" v-show="dialogShow">
            <div class="dialog" v-click-outside:dialog="handleDiaClickOutside">
                <header>{{dialogTit}}</header>
                <main class="dialogMain">
                    <el-form ref="form" :model="form" label-width="80px" size="mini" :rules="formRule">
                        <el-form-item label="项目" prop="depId">
                            <el-select v-model="form.depId" placeholder="请选择项目" class="fullWidth" @change="onChangeDepart">
                                <el-option :label="item.departName" :value="item.id" v-for="item in carProjectList" :key="item.id"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="车场">
                            <!-- <el-select v-model="form.parkId" placeholder="请选择车场" class="fullWidth" multiple @change="onChangeSelect">
                                <el-option :label="item.name" :value="item.id" v-for="item in carParkList" :key="item.id"></el-option>
                            </el-select> -->
                            <div class="borderWrap">
                                <el-checkbox :label="item.id" name="park" v-for="(item,index) in carParkList" :key="index" @change="(val)=>onChangeSelect(item,val)">{{item.name}}</el-checkbox>
                            </div>
                            <!-- <el-checkbox-group v-model="form.parkId">
                                <el-checkbox :value="item.id" name="park" v-for="(item,index) in carParkList" :key="index" >{{item.name}}</el-checkbox>
                            </el-checkbox-group> -->
                        </el-form-item>
                        <el-form-item label="车牌" prop="carNum">
                            <el-select v-model="form.carNum" placeholder="请选择车场" class="fullWidth">
                                <el-option :label="item.carNum" :value="item.carNum" v-for="item in myCarList" :key="item.id"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="姓名" prop="userName">
                            <el-input v-model="form.userName"></el-input>
                        </el-form-item>
                        <el-form-item label="住址" prop="userAddress">
                            <el-input v-model="form.userAddress"></el-input>
                        </el-form-item>
                        <el-form-item label="电话" prop="phone">
                            <el-input v-model="form.phone"></el-input>
                        </el-form-item>
                        <div class="uploadWrap">
                            <span class="label">车牌照片</span>
                            <el-upload
                                class="avatar-uploader"
                                action="string"
                                accept="image/*"
                                :show-file-list="false"
                                :before-upload="beforeUpload"
                                :on-change="handleChange"
                                :on-preview="handlePictureCardPreview"
                                :auto-upload="false"
                                > <!--  -->
                                <img v-if="imageUrl" :src="imageUrl" class="avatar">
                                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                            </el-upload>
                        </div>
                        <el-form-item>
                            <el-button type="primary" @click="onSubmit">提交</el-button>
                            <el-button @click="cancleHandle">取消</el-button>
                        </el-form-item>
                    </el-form>
                </main>
            </div>
        </div>
    </div>
</template>
<script>
import { mapGetters } from "vuex"
import { ImagePreview } from 'vant';
import ClickOutside from 'element-ui/src/utils/clickoutside'
import plateNumber from '@/components/plateNumber'
import {GetQueryByString,getDayNum,compress } from '@/utils'
import * as imageConversion from 'image-conversion';
import config from "@/api/config";
export default {
    components: {
        [ImagePreview.Component.name]: ImagePreview.Component,
        plateNumber
    },
    data(){
        return {
            searchVal:"",
            finished: false,
            loading: false,
            carProjectList:[],
            carParkList:[],
            myCarList:[],
            monthlyCarList:[],
            params:{
                userId:""
            },
            pageNo: 1,//请求第几页
            pageSize: 10,//每页请求的数量
            total: 0,//总共的数据条数
            dialogShow:false,
            dialogTit:"月租申请",
            form:{
                depId:"",
                departId:"",
                parkId:[],
                parkNames:[],
                carNum:"",
                userName:"",
                userAddress:"",
                phone:"",
                file:''
            },
            formParams:{
                parkId:'',
                parkNames:''
            },
            formRule:{
                depId: [
                    { required: true, message: '请选择项目', trigger: 'change' }
                ],
                parkId: [
                    { required: true, message: '请选择车场', trigger: 'change' }
                ],
                carNum: [
                    { required: true, message: '请选择车场', trigger: 'change' }
                ],
                userName: [
                    { required: true, message: '姓名不能为空', trigger: 'blur' }
                ],
                userAddress: [
                    { required: true, message: '地址不能为空', trigger: 'blur' }
                ],
                phone: [
                    { required: true, message: '手机号不能为空', trigger: 'blur' },
                    { pattern:/^((0\d{2,3}-\d{7,8})|(1[3584]\d{9}))$/, message: "请输入合法手机号/电话号", trigger: "blur" }
                ],
            },
            imageUrl:"",
            dialogVisible:false,
            appID:config.appID||sessionStorage.getItem('appId')
        }
    },
    directives: { ClickOutside },
    computed: {
        ...mapGetters(['user'])
    },
    created(){
        this.initDataFn()
        /* let dayNum = getDayNum("2020-12-24")
        console.log(dayNum,"dayNum") */
    },
    methods:{
        initDataFn(){
            try {
                const url=window.location.href;//获取当前地址栏
                const aid=GetQueryByString(url,'aid');//GetQueryByString 自己封装的方法来获取地址栏的参数
                let start=url.indexOf("code");
                const code=url.substr(start+5,32);
                //alert(code)
                if (start>=0){//如果存在code
                    this.loading = true;
                    const toast = this.$toast.loading({
                        duration: 0, // 持续展示 toast
                        forbidClick: true,
                        message: "加载中..."
                    });
                    let formData = new FormData();
                        formData.append('code',code)
                        formData.append('type',1)
                        formData.append('appId',config.appID)
                    this.$api.owner.wxlogin(formData)  //code作为换取access_token的票据，每次用户授权带上的code将不一样，code只能使用一次，5分钟未被使用自动过期。
                        .then(res => {
                            this.$toast.clear();
                            this.loading = false;
                            console.log(res,"ownerwxlogin")
                            //alert(JSON.stringify(res))
                            if(res.code == 200){
                                //this.$store.dispatch('setDepId', res.result.merInfo.depId)
                                this.$store.dispatch('setUser', res.result.userInfo)
                                this.$store.dispatch('setVipUser', res.result.vipUser)
                                if(res.result.userInfo){                            
                                    sessionStorage.setItem('userId',res.result.userInfo.id)
                                }
                                sessionStorage.setItem('vipMoney',res.result.vipUser.money)
                                //this.$store.dispatch('setOrgCategory', res.result.park.orgCategory)
                                sessionStorage.setItem('token',res.result.token)
                                this.params.userId = this.$route.query.userId||this.user.id||sessionStorage.getItem('userId')
                                this.init()
                                this.getCarList()
                                console.log(this.appID,'appID')
                            }else if(res.code == 201){
                                /* window.location.replace(
                                    window.location.origin + "/loginOwner?openid="+res.message
                                ); */
                                this.$router.push({
                                    path:"/loginOwner",
                                    query:{
                                        openid:res.message,
                                        appId:config.appID
                                    }
                                })
                            }
                        })
                        .catch(err => {
                            this.$toast.clear();
                        });
                }else{
                    this.params.userId = this.$route.query.userId||this.user.id||sessionStorage.getItem('userId')
                    this.init()
                    this.getCarList()
                    console.log(this.appID,'appID')
                }
            } catch (err) {
                console.log(err)
            }
        },
        getDayNum:getDayNum,
        getPlateLicense(data){
            this.form.carNum = data
        },
        //返回
        onClickLeft(){
            this.$router.push('/indexOwner')
        },
        getCarList(){
            this.$api.owner.getCarList().then(res=>{
                if(res.code == 200){
                    let rows = res.result; //请求返回当页的列表
                    this.carProjectList = rows
                }else{
                    this.$toast(res.message);
                }
            }).catch((res) => {
                this.loading = false;
            });
        },
        async init(){
            const toast = this.$toast.loading({
                duration: 0, // 持续展示 toast
                forbidClick: true,
                message: "加载中..."
            });
            await this.$api.owner.getMonthlyCarList(this.params).then(res=>{
                if(res.code == 200){
                    //debugger
                    let rows = res.result; //请求返回当页的列表
                    this.monthlyCarList = rows||[]
                    this.finished = true
                }else{
                    this.finished = true
                    this.$toast(res.message);
                }
            }).catch((res) => {
                this.loading = false;
            });
            await this.$api.owner.getMyCarList(this.params).then(res=>{
                this.$toast.clear();
                if(res.code == 200){
                    if(res.result&&res.result.length>0){
                        let rows = res.result; //请求返回当页的列表
                        this.myCarList = rows
                    }                    
                }else{
                    this.$toast(res.message);
                }
                this.loading = false;
            }).catch((res) => {
                this.$toast.clear();
                this.loading = false;
            });
        },
        apply(){
            this.dialogShow = true
            this.$nextTick(()=>{
                this.$refs['form']&&this.$refs['form'].resetFields()
            })
        },
        jumpPay(item){
            //debugger
            this.$router.push({
                path:"/renew",
                query:{
                    carInfo:item
                }
            })
        },
        pay(item){
            let domT = ''
            //   let ua = navigator.userAgent.toLowerCase()
            if (/MicroMessenger/.test(window.navigator.userAgent)) {
                domT = 'weixin'
            }
            if (/AlipayClient/.test(window.navigator.userAgent)) {
                domT = 'alipay'
            }
            let that = this
            let data = {
                channel: domT, 
                recordId: item.id
            }
            let formData = new FormData();
                formData.append('channel','weixin');
                formData.append('recordId',item.id);
            this.$api.owner.getpayadress(formData).then(res => {
                if (res.code === 200) {
                    window.location.href = res.result
                } else {
                    this.$toast(`${res.message}`)
                }
            }).catch(error => {
                this.$toast(`${error}`)
            })
        },
        onChangeDepart(val){
            //debugger
            let array = this.carProjectList
            for (let i = 0; i < array.length; i++) {
                const item = array[i];
                if(item.id==val){
                    this.carParkList = item.parkList
                }
            }
        },
        onChangeSelect(item,flg){
            //debugger
            if(flg){
                this.form.parkId.push(item.id)
                this.form.parkNames.push(item.name)
            }else{
                let parkIds = this.form.parkId
                parkIds&&parkIds.splice(parkIds.findIndex(e => e === item.id), 1)
                let parkNames = this.form.parkNames
                parkNames&&parkNames.splice(parkNames.findIndex(e => e === item.name), 1)
            }
            /* this.form.parkNames = []
            let array = this.carParkList
            for (let i = 0; i < array.length; i++) {
                const item = array[i];
                for (let j = 0; j < val.length; j++) {
                    const element = val[j];
                    if(item.id==element){
                        this.form.parkNames.push(item.name)
                    }
                }
            } */
        },
        handleChange(file, fileList){
            //debugger
            let fileObj = file.raw
            let that = this
            return new Promise((resolve, reject) => {
                let _URL = window.URL || window.webkitURL
                let isLt2M = file.size / 1024 / 1024 < 10 // 判定图片大小是否小于4MB
                // 这里需要计算出图片的长宽
                let img = new Image()                                                     
                // 需要把图片赋值
                img.src = URL.createObjectURL(fileObj)
                that.imageUrl = URL.createObjectURL(fileObj)
                img.onload = function () {
                    fileObj.width = img.width // 获取到width放在了file属性上
                    fileObj.height = img.height // 获取到height放在了file属性上
                    let valid = img.width > 2000 // 图片宽度大于2000
                    // console.log(11, file)
                    // 这里我只判断了图片的宽度,compressAccurately有多个参数时传入对象
                    if (isLt2M) {
                        imageConversion.compress(fileObj, {
                            quality: 0.7,
                            width: 500,
                            type: "image/png", 
                        }).then(res => { 
                            console.log("压缩后图片", res)
                            const resAvatarFile = new window.File(
                                [res],
                                fileObj.name,
                                { type: fileObj.type },
                            );
                            //debugger
                            that.form.file = resAvatarFile;
                            resolve(res)
                        })
                    } else {
                        this.$message.error('上传头像图片大小不能超过 10MB!');
                    }
                }
            })
            /* this.imageUrl = URL.createObjectURL(fileObj);
            this.form.file = fileObj */
        },
        beforeUpload(file){
            const isLt2M = file.size / 1024 / 1024 < 1;
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 1MB!');
            }
            return isJPG && isLt2M;
        },
        onSubmit(){
            if(this.form.parkId.length==0){
                this.$message.error('请选择车场！');
                return false
            }else{
                //debugger
                this.formParams.parkId = this.form.parkId.join(',')
                this.formParams.parkNames = this.form.parkNames.join(',')
            }
            console.log(this.form,'this.form');
            console.log(this.formParams,'this.formParams');
            //debugger
            this.$refs['form'].validate((valid) => {
                if (valid) { 
                    if(this.form.file==''){
                        this.$message.error('请上传图片！');
                        return false
                    }
                    const toast = this.$toast.loading({
                        duration: 0, // 持续展示 toast
                        forbidClick: true,
                        message: "加载中..."
                    });
                    let formData = new FormData()
                        formData.append('depId',this.form.depId)
                        formData.append('parkId',this.form.parkId)
                        //formData.append('parkNames',this.form.parkNames)
                        formData.append('carNum',this.form.carNum)
                        formData.append('userId',this.params.userId)
                        formData.append('userName',this.form.userName)
                        formData.append('userAddress',this.form.userAddress)
                        formData.append('phone',this.form.phone)
                        formData.append('file',this.form.file)
                    //debugger
                    this.$api.owner.applyMonthCar(formData).then(res=>{
                        this.$toast.clear();
                        if (res.code === 200) {
                            //debugger
                            this.cancleHandle()
                            this.init()
                        } else {
                            this.$toast(`${res.message}`)
                        }
                    }).catch(error => {
                        this.$toast.clear();
                        this.$toast(`${error}`)
                    })
                } else {
                        console.log('error submit!!');
                        return false;
                    }
                });
        },
        cancleHandle(){
            this.dialogShow = false
            this.imageUrl = ""
            this.carParkList = []
            this.form = {
                depId:"",
                departId:"",
                parkId:[],
                parkNames:[],
                carNum:"",
                userName:"",
                userAddress:"",
                phone:"",
                file:''
            }
            this.formParams={
                parkId:'',
                parkNames:''
            }
        }
    }
}
</script>
<style lang="less" scoped>
    .dialogMain{
        padding: .3rem;
        .uploadWrap{
            width: 100%;
        }
        .carNum{
            width: 100%;
            margin-bottom: 10px;
            /deep/ .wrap{
                padding: 0;
                border-bottom:0;
                .singleBlock{
                    display: inline-block;
                    width: 100%;
                }
                .card-header{
                    float: left;
                    display: inline-block;
                    width: 70px;
                    padding-right:12px;
                    margin:0;
                }
                .num-box{
                    display: inline-flex;
                    width: calc(100% - 70px);
                }
            }
        }
        .label{
            line-height: 28px;
            text-align: right;
            vertical-align: middle;
            float: left;
            font-size: 14px;
            color: #606266;
            padding: 0 12px 0 0;
            box-sizing: border-box;
        }
        .avatar-uploader {
            /deep/ .el-upload {
                width: 100%;
                height:4rem;
                line-height: 4rem;
                border: 1px dashed #d9d9d9;
                border-radius: 6px;
                cursor: pointer;
                position: relative;
                overflow: hidden;
            }
            .el-upload:hover {
                border-color: #409EFF;
            }            
            .avatar-uploader-icon {
                font-size: 28px;
                color: #8c939d;
                width: 100%;
                height: 3rem;
                line-height: 3rem;
                text-align: center;
            }
            .avatar {
                max-width: 100%;
                margin: auto;
                vertical-align: middle;
            }
        }
    }
    .borderWrap{
        min-height: 30px;
        padding: 0 .1rem;
        border:1px solid #DCDFE6;
        border-radius: 4px;
    }
    .fullWidth{
        width: 100%;
    }
</style>